package local

import (
	"oa-rest/common"
	"github.com/gin-gonic/gin"
)

// QueryHandler 处理查询请求
func QueryHandler(query, mode, responseType string, includeReferences bool) (*LocalQueryResponse, error) {
	// 创建临时服务实例
	service := NewLocalQueryService()

	// 执行查询
	return service.LocalQuery(query, mode, responseType, includeReferences)
}

// LocalQueryHandler 本地查询请求处理器
func LocalQueryHandler(c *gin.Context) {
	var res common.Response
	var req LocalQueryRequest

	// 绑定请求参数
	if err := c.ShouldBindJSON(&req); err != nil {
		res.Format(c, "参数解析失败: "+err.Error())
		return
	}

	// 参数验证
	if req.Query == "" {
		res.Format(c, "查询内容不能为空")
		return
	}

	// 设置默认值
	if req.Mode == "" {
		req.Mode = "local"
	}
	if req.ResponseType == "" {
		req.ResponseType = "Detailed"
	}

	// 调用本地查询服务
	result, err := QueryHandler(req.Query, req.Mode, req.ResponseType, req.IncludeReferences)
	if err != nil {
		res.Format(c, "查询失败: "+err.Error())
		return
	}

	res.Data = result
	res.Format(c)
}

// LocalQueryFormHandler 表单形式的查询处理器
func LocalQueryFormHandler(c *gin.Context) {
	var res common.Response

	// 从表单获取参数
	query := c.PostForm("query")
	mode := c.PostForm("mode")
	responseType := c.PostForm("response_type")
	includeReferences := c.PostForm("include_references") == "true"

	// 参数验证
	if query == "" {
		res.Format(c, "查询内容不能为空")
		return
	}

	// 设置默认值
	if mode == "" {
		mode = "local"
	}
	if responseType == "" {
		responseType = "Detailed"
	}

	// 调用本地查询服务
	result, err := QueryHandler(query, mode, responseType, includeReferences)
	if err != nil {
		res.Format(c, "查询失败: "+err.Error())
		return
	}

	res.Data = result
	res.Format(c)
}